package com.sh.caryr.erp.service.impl;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sh.caryr.erp.service.external.entity.ExtProduct;
import com.sh.caryr.erp.entity.product.Product;
import com.sh.caryr.erp.entity.product.ProductMapping;
import com.sh.caryr.erp.mapper.ProductMappingMapper;
import com.sh.caryr.erp.service.IProductMappingService;
import com.sh.caryr.erp.service.IProductService;
import com.sh.caryr.erp.service.external.helper.ExtServiceHelper;
import com.sh.caryr.erp.util.MyBatisUtil;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductMappingServiceImpl extends ServiceImpl<ProductMappingMapper, ProductMapping> implements IProductMappingService {

    @Autowired
    private ProductMappingMapper mapper;

    @Autowired
    private IProductService productService;

    @Override
    public List<ProductMapping> findDetailListDynamic(Integer current, Integer size, Wrapper wrapper) {
        return mapper.selectListDetails(new RowBounds(MyBatisUtil.offset(current, size), size), wrapper);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void genProductSpecByProMappings(List<ExtProduct> extProducts, List<ProductMapping> productMappings) {
        // Insert products. TODO batch insert to improve performance.
        for (ProductMapping mapping : productMappings) {
            if (mapping.getProductSpecId() == null) {
                Product product = ExtServiceHelper.generateProductByProMapping(extProducts, mapping);
                productService.insertProduct(product);
                //Set back proSpecId for productMapping
                mapping.setProductSpecId(product.getProductSpecList().get(0).getId());
            }
        }
        // Update proSpecId for productMappings
        this.updateBatchById(productMappings);
    }

}
